﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.IO;

namespace Wicresoft.RDW.Helper
{
    public class UploadFile
    {
       
        public bool Upload(HttpPostedFile pic, string mapPath)
        {
            InitDirectory(mapPath);
            if (!CheckFileExt(pic))
            {
                return false;
            }
            string ext = Path.GetExtension(pic.FileName).ToLower();
            string picName = Path.GetFileNameWithoutExtension(pic.FileName) + "-" + GetRandomNumber() + ext;
            string filePath = Path.Combine(mapPath, picName);
            pic.SaveAs(filePath);
            return true;
        }
        private void InitDirectory(string mapPath)
        {
            if (!Directory.Exists(mapPath))
            {
                Directory.CreateDirectory(mapPath);
            }
        }
        private bool CheckFileExt(HttpPostedFile file)
        {
            string ext = Path.GetExtension(file.FileName).ToLower().Replace(".", "");
            string[] extList = ConfigurationManager.AppSettings["Picture"].Split(',');
            foreach (string extItem in extList)
            {
                if (ext == extItem)
                {
                    return true;
                }
            }
            return false;
        }
        private int GetRandomNumber()
        {
            Random random = new Random();
            return (10000 + random.Next(1, 90000));
        }
    }
}